package it.univaq.di.helpdesk.common;

import it.univaq.di.helpdesk.business.common.HelpDeskServiceFactory;
import it.univaq.di.helpdesk.business.common.UserService;
import it.univaq.di.helpdesk.business.errors.AccountLockedException;
import it.univaq.di.helpdesk.business.errors.BusinessException;
import it.univaq.di.helpdesk.business.model.Role;
import it.univaq.di.helpdesk.business.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.securityfilter.realm.SimpleSecurityRealmBase;


public class HelpDeskRealm extends SimpleSecurityRealmBase {
	private Log logger = LogFactory.getLog(HelpDeskRealm.class);
	
	@Override
    public boolean booleanAuthenticate(String username, String password,
			HttpServletRequest request) {

		if (username == null || username.length() == 0 || password == null
				|| password.length() == 0) {
			return false;
		}
		
		UserService service = HelpDeskServiceFactory.getInstance()
				.getUserService();
		
		try {
			User user = service.authenticate(username, password);
			if (user != null) {
				// Elimino la password dall'oggetto messo in sessione
				user.setPassword("");
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				return true;
			} else {
				return false;
			}
		} catch (AccountLockedException e) {
			request.setAttribute("locked", true);
			//System.err.println(e.getMessage());
			logger.debug("User account locked: " + request.getRequestURI(), e); 
			return false;
		} catch (BusinessException e) {
			/*System.err.println("Error occurred during user authentication");
			System.err.println(e.getMessage());
			System.err.println(e.getCause());*/
			logger.error("An arror occurred while processing user authentication: "+ 
						 request.getRequestURI(), e);
			return false;
		}
	}

	@Override
	public boolean isUserInRole(String username, String rolename,
			HttpServletRequest request) {
		HttpSession session = request.getSession();
        User user = ( User ) session.getAttribute( "user" );
        
		for (Role role : user.getRoles()) {
			if ( role.getName().equals(rolename) ) {
				return true;
			}
		}
		return false;
	}
}
